package org.sagitta.httprpc;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.message.Request;
import org.sagitta.httprpc.message.Response;

@SuppressWarnings("unchecked")
class WebAction {
	private static final Log log = LogFactory.getLog(WebAction.class);
	private ControllerBase controller;
	private Method actionMethod;
	private Class requestClazz;
	
	public WebAction(ControllerBase controller, Method actionMethod, Class requestClazz) {
		this.controller = controller;
		this.actionMethod = actionMethod;
		this.requestClazz = requestClazz;
	}
	
	public Response invoke(Request request) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("invoking " + controller.getClass().getName() + "[" + actionMethod.getName() + "]");
		}
		controller.beforeInvoke(request, this.actionMethod.getName());
		Object result = actionMethod.invoke(controller, request);
		Response response = (result instanceof Response) ? (Response)result : null;
		controller.afterInvoke(response, this.actionMethod.getName());
		return response;
	}
	
	public Class getRequestClassType() {
		return requestClazz;
	}
	
}
